package iotwisp.base.cqrs;

import com.alibaba.fastjson.annotation.JSONField;

import iotwisp.base.cqrs.unitofwork.UnitOfWork;
import iotwisp.base.util.UUIDGenerator;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.Date;

@Data
public class BaseCommand implements Serializable {

	/**
	 * 命令id
	 */
	private String commandId = UUIDGenerator.getUUID();

	/**
	 * 创建时间
	 */
	private Date cmdCreateDate;

	/**
	 * 命令处理结束时间
	 */
	private Date finishDate;

	/**
	 * 操作所属的流程id
	 */
	private String sagaId;

	private UnitOfWork unitOfWork;

	private Boolean cleanUnitOfWork = false;

	// public BaseEvent happen(String exchange, String describe, String topic,
	// String topicKey, Object payload, String developer) {
	// return getUnitOfWork().generateEvent(exchange, describe, topic, topicKey,
	// payload, developer);
	// }
	//
	@JSONField(serialize = false)
	public UnitOfWork getUnitOfWork() {

		if (StringUtils.isBlank(commandId)) {
			setCommandId(UUIDGenerator.getUUID());
		}

		if (this.unitOfWork == null) {
			setUnitOfWork(UnitOfWork.getInstance(commandId, getSagaId()));
			setCleanUnitOfWork(true);
		}

		return this.unitOfWork;
	}

	@Override
	public String toString() {
		return "BaseCommand [commandId=" + commandId + ", cmdCreateDate=" + cmdCreateDate + ", finishDate=" + finishDate
				+ ", sagaId=" + sagaId + ", unitOfWork=" + unitOfWork + ", cleanUnitOfWork=" + cleanUnitOfWork + "]";
	}
	
}
